package com.example.intermediateactivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;

import androidx.appcompat.app.AppCompatActivity;

import com.example.intermediateactivity.utils.ToastHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class SpinnerDropdownSimpleIcon extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    private ArrayList<Map<String, Object>> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner_dropdown_simple_icon);

        // 列表项目的内容，用Map存储，共有2对，分别对应： icon:图标， name:文字
        HashMap<String, Object> item1 = new HashMap<>();
        item1.put("icon", R.drawable.pic1);
        item1.put("name", "哈士奇");

        HashMap<String, Object> item2 = new HashMap<>();
        item2.put("icon", R.drawable.pic2);
        item2.put("name", "小白狗");

        HashMap<String, Object> item3 = new HashMap<>();
        item3.put("icon", R.drawable.pic3);
        item3.put("name", "小白猫");

        HashMap<String, Object> item4 = new HashMap<>();
        item4.put("icon", R.drawable.pic4);
        item4.put("name", "小花猫");

        // 使用List存储所有的列表项数据
        list = new ArrayList<>();
        list.add(item1);
        list.add(item2);
        list.add(item3);
        list.add(item4);

        // 创建SimpleAdapter用列表，
        // 参数4为map的所有key
        // 参数5为对应的值 用于的 元素的id
        SimpleAdapter simpleAdapter = new SimpleAdapter(
                this,
                list,
                R.layout.spinner_item_icon,
                new String[]{"icon", "name"},
                new int[]{R.id.iv_icon, R.id.tv_name}
        );

        Spinner iconList = findViewById(R.id.sp_simple_icon);
        // 给列表容器设置适配器
        iconList.setAdapter(simpleAdapter);
        iconList.setSelection(0);

        iconList.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        ToastHelper.show(this, "您选择了" + list.get(i).get("name"));
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }
}